import java.util.HashSet;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Set;

public class Work04 {
    static String target = "087654321";

    public static void main(String[] args) {
        bfs();
        System.out.println(1);
    }

    static Set<String> set = new HashSet<String>();
    static int[] dir = new int[] { -2, -1, 1, 2 };
    public static void bfs() {
        Queue<String> que = new LinkedList<String>();
        que.add("012345678");
        set.add("012345678");
        int ans = 0;
        while (!que.isEmpty()) {
            int size = que.size();
            for (int k = 0; k < size; ++k) {
                String p = que.poll();
                if(p.equals(target)) {
                    System.out.println(ans);
                    return ;
                }
                char[] cp = p.toCharArray();
                int ind = 0;
                for (int i = 0; i < cp.length; ++i) {
                    if (cp[i] == '0') {
                        ind = i;
                        break;
                    }
                }
                for (int i = 0; i < dir.length; ++i) {
                    int nind = (ind + dir[i] + 9) % 9;
                    char[] temcp = cp.clone();
                    temcp[ind] = cp[nind];
                    temcp[nind] = cp[ind];
                    String strp = new String(temcp);
                    if (!set.contains(strp)) {
                        que.add(strp);
                        set.add(strp);
                    }
                }
            }
            ++ ans;
        }
    }
}
